package com.fcai.microserv.jwt.interceptor;

import com.fcai.microserv.jwt.FcaiJwtTokenManager;
import com.fcai.microserv.jwt.JwtConst;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 解析http请求中的jwt令牌
 */
public class JwtTokenParseInterceptor extends AbstractFcaiSecurityInterceptor {

    private FcaiJwtTokenManager tokenManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中取得身份令牌
        String jwtToken = request.getHeader(tokenManager.getHttpHeader());
        if (StringUtils.isBlank(jwtToken)) {
            return super.preHandle(request, response, handler);
        }

        Claims claims = tokenManager.parseJwtToken(jwtToken);
        String subjectType = claims.get(JwtConst.JWT_SUBJECT_TYPE, String.class);
        String subjectId = claims.get(JwtConst.JWT_SUBJECT_ID, String.class);

        request.setAttribute(JwtConst.CURRENT_USER_ID_HTTP_ATTR, subjectId);
        request.setAttribute(JwtConst.CURRENT_USER_TYPE_HTTP_ATTR, subjectType);
        return super.preHandle(request, response, handler);
    }

}
